import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/entity/selectiont_entity.dart';
import 'package:shopping_group/entity/widget_entity.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/person/bloc/add_address_bloc.dart';
import 'package:shopping_group/modle/person/entity/soujianren_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';

class AddAdressPage extends StatefulWidget {
  final String action;
  final SouJianRenEntity entity;
  AddAdressPage({
    Key key,
    this.entity,
    @required this.action,
  }) : super(key: key);

  @override
  _AddAdressPageState createState() => _AddAdressPageState();
}

class _AddAdressPageState extends State<AddAdressPage> {
  Map<String, dynamic> _cityAdress = {};
  WidgetEntity _nameWidgetEntity = WidgetEntity();
  WidgetEntity _phoneWidgetEntity = WidgetEntity();
  WidgetEntity _adressWidgetEntity = WidgetEntity();
  List<SelectiontEntity> _selectiontListEntity = [];
  AddAddressBloc _bloc;
  StreamSubscription _refresSubscription;

  @override
  void initState() {
    super.initState();
    _bloc = AddAddressBloc();
    if (null != this.widget.entity &&
        !ObjectUtil.isEmptyString(this.widget.entity.id)) {
      _bloc.initDate.add(this.widget.entity.id);
    } else {
      _bloc.initDate.add(null);
    }
    _refresSubscription = eventBus.on<OneSouJianRenEvent>().listen((event) {
      if (null != event && null != event.entity) {
        _nameWidgetEntity.controller.text =
            Utils.reTextNull(event.entity.souJianRenName);
        _phoneWidgetEntity.controller.text =
            Utils.reTextNull(event.entity.souJianRenPhone);
        _adressWidgetEntity.controller.text =
            Utils.reTextNull(event.entity.souJianRenAddress);
        setState(() {
          _cityAdress['provinceName'] = event.entity.souJianRenProvName;
          _cityAdress['provinceId'] = event.entity.souJianRenProv;
          _cityAdress['cityName'] = event.entity.souJianRenCityName;
          _cityAdress['cityId'] = event.entity.souJianRenCity;
          _cityAdress['areaName'] = event.entity.souJianRenTownName;
          _cityAdress['areaId'] = event.entity.souJianRenTownName;
          _cityAddrss(event.entity);
        });
      }
    });

    _cityAdress['cityName'] = '请选择';
    _nameWidgetEntity = WidgetUtils.initEditText(
        '收件人：', '', '请输入收件人姓名', 'all', TextEditingController());
    _phoneWidgetEntity = WidgetUtils.initEditText(
        '手机号码：', '', '请输入手机号码', 'number', TextEditingController());
    _adressWidgetEntity = WidgetUtils.initEditText(
        '详细地址：', '', '请输入详细地址', 'all', TextEditingController());

    _selectiontListEntity
      ..add(SelectiontEntity()
        ..id = '家'
        ..color = Colours.gray_91
        ..blackColor = Colours.gray_91)
      ..add(SelectiontEntity()
        ..id = '公司'
        ..color = Colours.gray_91
        ..blackColor = Colours.gray_91)
      ..add(SelectiontEntity()
        ..id = '学校'
        ..color = Colours.gray_91
        ..blackColor = Colours.gray_91)
      ..add(SelectiontEntity()
        ..id = '其它'
        ..color = Colours.gray_91
        ..blackColor = Colours.gray_91);
  }

  Map<String, dynamic> _cityAddrss(SouJianRenEntity result) {
    StringBuffer stringBuffer = StringBuffer();
    stringBuffer
      ..write(result.souJianRenProvName)
      ..write('  ')
      ..write(result.souJianRenCityName)
      ..write('  ')
      ..write(result.souJianRenTownName);
    _cityAdress['adress'] = stringBuffer.toString();
    return result.cityAdress;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(
          context, null == this.widget.action ? '新增地址' : this.widget.action),
      body: Container(
        decoration: new BoxDecoration(
          color: Colors.white,
        ),
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          reverse: false,
          padding: EdgeInsets.all(0.0),
          physics: BouncingScrollPhysics(),
          child: Column(
            children: <Widget>[
              WidgetUtils.showEditText(_nameWidgetEntity),
              WidgetUtils.showEditText(_phoneWidgetEntity),
              _selectCity(),
              WidgetUtils.showEditText(_adressWidgetEntity),
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    WidgetUtils.getTextColorView(
                      '标签',
                      Colours.text_2222,
                      Dimens.FONT_SIZE_16,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children:
                          _selectiontListEntity.map((SelectiontEntity entity) {
                        return Padding(
                            padding: EdgeInsets.only(right: 4),
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  for (var item in _selectiontListEntity) {
                                    item
                                      ..color = Colours.gray_91
                                      ..blackColor = Colours.gray_91
                                      ..isSelect = false;
                                  }
                                  entity
                                    ..color = Colours.title_white
                                    ..blackColor = Colours.themeColor
                                    ..isSelect = true;
                                });
                              },
                              child: WidgetUtils.showBoxBotton(entity.id,
                                  borderColor: entity.blackColor,
                                  textColor: entity.color,
                                  boxColor: entity.isSelect
                                      ? entity.blackColor
                                      : Colours.transparent,
                                  horizontalPadding: '家' == entity.id ? 16 : 8),
                            ));
                      }).toList(),
                    ),
                  ],
                ),
              ),
              WidgetUtils.drawCodeDivider(height: 1),
              Container(
                alignment: Alignment.centerLeft,
                padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: WidgetUtils.getTextColorView(
                  '设置为默认地址',
                  Colours.text_2222,
                  Dimens.FONT_SIZE_16,
                ),
              ),
              WidgetUtils.drawCodeDivider(height: 1),
              SizedBox(
                height: 32,
              ),
              _bomttonView(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _selectCity() {
    return WidgetUtils.selectCity('选择省市区：', _cityAdress, context,
        adressCallBlack: (data) {
      setState(() {
        _cityAdress = data;
      });
    });
  }

  Widget _bomttonView() {
    return ButtonProgressView.crateCupertinoView('保存地址', cupertinoCall: () {
      Map<String, dynamic> data = {};
      if (!ObjectUtil.isEmptyMap(_cityAdress)) {
        data['souJianRenProv'] = _cityAdress['provinceId'];
        data['souJianRenCity'] = _cityAdress['cityId'];
        data['souJianRenTown'] = _cityAdress['areaId'];
        data['souJianRenProvName'] = _cityAdress['provinceName'];
        data['souJianRenCityName'] = _cityAdress['cityName'];
        data['souJianRenTownName'] = _cityAdress['areaName'];
      }
      String name = _nameWidgetEntity.controller.text;
      String phone = _phoneWidgetEntity.controller.text;
      String adress = _adressWidgetEntity.controller.text;
      data['id'] = (null == this.widget.entity ||
              ObjectUtil.isEmptyString(this.widget.entity.id))
          ? ''
          : this.widget.entity.id;
      data['userId'] = BaseConstant.userId;
      data['souJianRenName'] = name;
      data['souJianRenPhone'] = phone;
      data['souJianRenAddress'] = adress;

      _bloc.addAddressDate.add(data);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _nameWidgetEntity.controller?.clear();
    _phoneWidgetEntity.controller?.clear();
    _adressWidgetEntity.controller?.clear();
    _refresSubscription?.cancel();
  }
}
